package com.example.juc.readAndWrite;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class ReadAndWriteDemo {
    public static void main(String[] args) {
        MyCache myCache = new MyCache();
        for (int i =1;i<=5;i++){
            final int temp = i;
            new Thread(()->{
                myCache.put(temp+"",temp+"");
            },String.valueOf(i)).start();
        }

        for (int i =1;i<=5;i++){
            final int temp = i;
            new Thread(()->{
                myCache.get(temp+"");
            },String.valueOf(i)).start();
        }
    }
}



class MyCache2{

    private volatile Map<String,String> map = new HashMap<>();

    private ReadWriteLock lock = new ReentrantReadWriteLock(); // 读写锁

     // 只能有一个线程写入
    public void put(String key,String value){
        lock.writeLock().lock();
        try {
            System.out.println(Thread.currentThread().getName()+"写入"+key);
            map.put(key,value);
            System.out.println(Thread.currentThread().getName()+"写入完成");
        }finally {
            lock.writeLock().unlock();
        }
    }

   // 多个线程可以读
    public String get(String key){
        lock.readLock().lock();
        try {
            System.out.println(Thread.currentThread().getName()+"读取"+key);
            String s = map.get(key);
            System.out.println(Thread.currentThread().getName()+"读取完成");
            return s;
        }finally {
            lock.readLock().unlock();
        }
    }
}





class MyCache{

    private volatile Map<String,String> map = new HashMap<>();

    public void put(String key,String value){
        System.out.println(Thread.currentThread().getName()+"写入"+key);
        map.put(key,value);
        System.out.println(Thread.currentThread().getName()+"写入完成");
    }


    public String get(String key){
        System.out.println(Thread.currentThread().getName()+"读取"+key);
        String s = map.get(key);
        System.out.println(Thread.currentThread().getName()+"读取完成");
        return s;
    }
}